#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        printf("Usage: ./recover IMAGE\n");
        return 1;
    }

    FILE *input = fopen(argv[1], "r");
    if (input == NULL)
    {
        printf("Could not open file.\n");
        return 1;
    }

    unsigned char buffer[512];

    int count_image = 0;

    FILE *output = NULL;

    char *filename = malloc(8 * sizeof(char));
    if (filename == NULL)
    {
        printf("Memory allocation failed.\n");
        fclose(input);
        return 1;
    }

    while (fread(buffer, sizeof(char), 512, input) == 512)
    {
        // 检查是否为JPEG文件起始标志
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff &&
            (buffer[3] & 0xf0) == 0xe0)
        {
            // 如果已经有打开的输出文件的话就先关闭掉
            if (output != NULL)
            {
                fclose(output);
            }

            // 为新图像按次序命名并打开输出文件
            sprintf(filename, "%03i.jpg", count_image);

            output = fopen(filename, "w");
            if (output == NULL)
            {
                printf("Could not create file %s\n", filename);
                free(filename);
                fclose(input);
                return 1;
            }

            count_image++;
        }

        if (output != NULL)
        {
            fwrite(buffer, sizeof(char), 512, output);
        }
    }

    // 关闭最后一个输出的文件
    if (output != NULL)
    {
        fclose(output);
    }
    // 释放动态分配的内存
    free(filename);

    fclose(input);
    return 0;
}
